<?php
/**
 * Created by PhpStorm.
 * User: dingjinlai
 * Date: 2019/5/5
 * Time: 上午11:00
 */

require_once __DIR__ . '/Google/vendor/autoload.php';

class Google_api
{
    private $analytics;

    public function __construct()
    {
        $this->analytics = $this->initializeAnalytics();
    }

    /**
     * Initializes an Analytics Reporting API V4 service object.
     *
     * @return An authorized Analytics Reporting API V4 service object.
     */
    public function initializeAnalytics()
    {

        // Use the developers console and download your service account
        // credentials in JSON format. Place them in this directory or
        // change the key file location if necessary.
        $KEY_FILE_LOCATION = __DIR__ . '/Google/my-data-60096-a08f061d186a.json';

        // Create and configure a new client object.
        $client = new Google_Client();
        $client->setApplicationName("Hello Analytics Reporting");
        $client->setAuthConfig($KEY_FILE_LOCATION);
        $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
        $analytics = new Google_Service_AnalyticsReporting($client);

        return $analytics;
    }

    /**
     * Queries the Analytics Reporting API V4.
     *
     * @param service An authorized Analytics Reporting API V4 service object.
     * @return The Analytics Reporting API V4 response.
     */
    public function getReport($view_id = '', $start_time = '', $end_time = '') {

        // Replace with your view ID, for example XXXX.
        if (!$view_id) {
            return false;
        }

        if ($start_time && $end_time) {
            $start_date = date('Y-m-d', $start_time);
            $end_date = date('Y-m-d', $end_time);

        } else {
            return false;
        }

        // Create the DateRange object.
        $dateRange = new Google_Service_AnalyticsReporting_DateRange();
        $dateRange->setStartDate($start_date);
        $dateRange->setEndDate($end_date);


        // Create the Metrics object.
        $productDetailViews = new Google_Service_AnalyticsReporting_Metric();
        $productDetailViews->setExpression("ga:productDetailViews");
        $productDetailViews->setAlias("productDetailViews");

        $productAddsToCart = new Google_Service_AnalyticsReporting_Metric();
        $productAddsToCart->setExpression("ga:productAddsToCart");
        $productAddsToCart->setAlias("productAddsToCart");

        $itemQuantity = new Google_Service_AnalyticsReporting_Metric();
        $itemQuantity->setExpression("ga:itemQuantity");
        $itemQuantity->setAlias("itemQuantity");

        //Create the Dimensions object.
        $browser = new Google_Service_AnalyticsReporting_Dimension();
        $browser->setName("ga:productSku");

        $ordering = new Google_Service_AnalyticsReporting_OrderBy();
        $ordering->setFieldName("ga:productDetailViews");
        $ordering->setSortOrder('DESCENDING');



        // Create the ReportRequest object.
        $request = new Google_Service_AnalyticsReporting_ReportRequest();
        $request->setViewId($view_id);
        $request->setDateRanges($dateRange);
        $request->setDimensions(array($browser));
        $request->setMetrics(array($productAddsToCart, $productDetailViews, $itemQuantity));
        $request->setOrderBys(array($ordering));
        $request->setPageSize(100000);

        $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
        $body->setReportRequests( array( $request) );
        $reports = $this->analytics->reports->batchGet( $body );

        $re = array(
            'date' => $start_date,
            'sku' => $this->printResults($reports)
        );

        return $re;
    }

    /**
     * Parses and prints the Analytics Reporting API V4 response.
     *
     * @param An Analytics Reporting API V4 response.
     */
    function printResults($reports) {

        $re = array();

        for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
            $report = $reports[ $reportIndex ];
            $header = $report->getColumnHeader();
            $dimensionHeaders = $header->getDimensions();
            $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
            $rows = $report->getData()->getRows();

            for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
                $row = $rows[ $rowIndex ];
                $dimensions = $row->getDimensions();
                $metrics = $row->getMetrics();
                for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
                    $re[$rowIndex][$dimensionHeaders[$i]] = $dimensions[$i];
                }

                for ($j = 0; $j < count($metrics); $j++) {
                    $values = $metrics[$j]->getValues();
                    for ($k = 0; $k < count($values); $k++) {
                        $entry = $metricHeaders[$k];
                        $re[$rowIndex][$entry->getName()] = $values[$k];
                    }
                }
            }
        }

        return $re;
    }

    function qgmdate($dateformat = 'Y-m-d H:i:s', $timestamp = '', $timeoffset = 8) {
        if(empty($timestamp)) {
            $timestamp = time();
        }
        $result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
        return $result;
    }
}
